//
//  AdressLTViewController.m
//  Contractor
//
//  Created by 金鑫 on 16/6/6.
//  Copyright © 2016年 star j. All rights reserved.
//

#import "AdressLTViewController.h"
#import "CONST.h"
#import "LocationModel.h"
#import "LocationTableViewCell.h"
#import "LocationCustomMenu.h"
#import "SetViewController.h"

@interface AdressLTViewController ()<UITableViewDelegate,UITableViewDataSource,LTCustomMenuDelegate>
{
    NSMutableArray *allArray ;
    NSMutableArray *provinceArray ;
    NSMutableArray *cityArray ;
    NSMutableArray *districtArray ;
    UITableView *locationTabelView ;
    NSMutableArray *MenuArray1 ;
    NSMutableArray *MenuArray2 ;
    NSMutableArray *MenuArray3 ;
    NSString *proviceStr ;
    NSString *cityStr ;
    NSString *districtStr ;
}

@end

@implementation AdressLTViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO ;
    self.navigationItem.title = @"修改区域" ;
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.edgesForExtendedLayout = UIRectEdgeBottom | UIRectEdgeLeft | UIRectEdgeRight;
    self.view.backgroundColor = [UIColor whiteColor] ;
    //[self downLoadlocation] ;
    
    NSUserDefaults *uidDefaults = [NSUserDefaults standardUserDefaults] ;
    
    NSData *data = [NSData dataWithData:[uidDefaults valueForKey:@"LocationArray"]] ;
    NSArray *array =  [NSKeyedUnarchiver unarchiveObjectWithData:data] ;
    allArray = [NSMutableArray arrayWithArray:array] ;
    NSLog(@"array:%lu",(unsigned long)array.count) ;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self initprovinceArray] ;
        
        LocationModel *model = [[LocationModel alloc] init] ;

        model = [self modelwithProvince:@"中国其他" city:@"中国其他" district:@"中国其他"] ;
        
        proviceStr = model.location1_cn ;
        cityStr = model.location2_cn ;
        districtStr = model.location3_cn ;
        
        [self initLocation] ;
        
        [self createTableView] ;
    }) ;
    
    UIButton *saveBtn = [[UIButton alloc] initWithFrame:CGRectMake(__kScreenWidth / 3, 230, __kScreenWidth/3, 50)] ;
    [saveBtn setTitle:@"确认" forState:UIControlStateNormal] ;
    [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal] ;
    saveBtn.backgroundColor = [UIColor blueColor] ;
    saveBtn.layer.cornerRadius = 5.0f ;
    [saveBtn addTarget:self action:@selector(save) forControlEvents:UIControlEventTouchUpInside] ;
    [self.view addSubview:saveBtn] ;
}

- (void)initLocation
{
    MenuArray1 = [NSMutableArray array] ;
    for (LocationModel *provinceModel in provinceArray) {
        NSLog(@"%@",provinceModel.location1_cn) ;
        [MenuArray1 addObject:provinceModel.location1_cn] ;
    }
    
    MenuArray2 = [NSMutableArray array] ;
    for (LocationModel *Model in cityArray) {
        NSLog(@"%@",Model.location2_cn) ;
        [MenuArray2 addObject:Model.location2_cn] ;
    }
    
    MenuArray3 = [NSMutableArray array] ;
    for (LocationModel *Model in districtArray) {
        NSLog(@"%@",Model.location3_cn) ;
        [MenuArray3 addObject:Model.location3_cn] ;
    }
    
}

- (void)createTableView
{
    locationTabelView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, __kScreenWidth, 153) style:UITableViewStylePlain] ;
    locationTabelView.separatorStyle = UITableViewCellSeparatorStyleNone ;
    locationTabelView.showsVerticalScrollIndicator = NO ;
    locationTabelView.scrollEnabled = NO ;
    locationTabelView.delegate = self ;
    locationTabelView.dataSource = self ;
    [self.view addSubview:locationTabelView] ;
}

- (void)initprovinceArray
{
    provinceArray = [NSMutableArray array] ;
    for (NSInteger i = 0; i < allArray.count; i++) {
        LocationModel *model = [[LocationModel alloc] init] ;
        model = allArray[i] ;
        if (provinceArray.count == 0) {
            [provinceArray addObject:model] ;
        }
        else if (provinceArray.count > 0) {
            LocationModel *provinceModel = [provinceArray lastObject] ;
            if (![model.location1 isEqualToString:provinceModel.location1]) {
                [provinceArray addObject:model] ;
            }
        }
    }
    NSLog(@"省份：%lu",(unsigned long)provinceArray.count) ;
    for (LocationModel *provinceModel in provinceArray) {
        NSLog(@"%@",provinceModel.location1_cn) ;
    }
    //    LocationModel *model = [[LocationModel alloc] init] ;
    //    model = provinceArray[1] ;
    //    [self initCityArray:model.location1] ;
}

- (void)initCityArray:(NSString *)province
{
    cityArray = [NSMutableArray array] ;
    [cityArray removeAllObjects] ;
    for (NSInteger i = 0; i < allArray.count; i++)
    {
        LocationModel *model = [[LocationModel alloc] init] ;
        model = allArray[i] ;
        if (cityArray.count == 0 && [model.location1_cn isEqualToString:province]) {
            [cityArray addObject:model] ;
        }
        if ([model.location1_cn isEqualToString:province] && cityArray.count > 0) {
            LocationModel *cityModel = [cityArray lastObject] ;
            if (![model.location2_cn isEqualToString:cityModel.location2_cn]) {
                [cityArray addObject:model] ;
            }
        }
    }
    NSLog(@"城市：%lu",(unsigned long)cityArray.count) ;
    for (LocationModel *cityModel in cityArray) {
        NSLog(@"%@---%@",cityModel.location1_cn,cityModel.location2_cn) ;
    }
    //    LocationModel *model = [[LocationModel alloc] init] ;
    //    model = cityArray[1] ;
    //    [self initdistrictArray:model.location1 city:model.location2] ;
}

- (void)initdistrictArray:(NSString *)province city:(NSString *)city
{
    districtArray = [NSMutableArray array] ;
    [districtArray removeAllObjects] ;
    for (NSInteger i = 0; i < allArray.count; i++)
    {
        LocationModel *model = [[LocationModel alloc] init] ;
        model = allArray[i] ;
        if (districtArray.count == 0 && [model.location1_cn isEqualToString:province] && [model.location2_cn isEqualToString:city]) {
            [districtArray addObject:model] ;
        }
        if (districtArray.count > 0 && [model.location1_cn isEqualToString:province] && [model.location2_cn isEqualToString:city]) {
            LocationModel *districtModel = [districtArray lastObject] ;
            if (![model.location3_cn isEqualToString:districtModel.location3_cn]) {
                [districtArray addObject:model] ;
            }
        }
        
    }
    
    for (LocationModel *districtModel in districtArray) {
        NSLog(@"%@---%@---%@",districtModel.location1_cn,districtModel.location2_cn,districtModel.location3_cn) ;
    }
    
}

- (LocationModel *)modelwithProvince:(NSString *)province city:(NSString *)city district:(NSString *)district
{
    [self initCityArray:province] ;
    [self initdistrictArray:province city:city] ;
    
    NSMutableArray *modelArray = [NSMutableArray array] ;
    for (LocationModel *model in districtArray) {
        if ([model.location1_cn isEqualToString:province] && [model.location2_cn isEqualToString:city] && [model.location3_cn isEqualToString:district]) {
            [modelArray addObject:model] ;
        }
    }
    
    return modelArray[0] ;
}

#pragma mark - TableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1 ;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3 ;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LocationTableViewCell *cell = [[LocationTableViewCell alloc] init] ;
    cell.selectionStyle = UITableViewCellSelectionStyleNone ;
    NSArray *titleArray = @[@"省份：",@"城市：",@"区域："] ;
    
    NSArray *dataArray = @[proviceStr,cityStr,districtStr] ;
    [cell configTitle:titleArray[indexPath.row] withData:dataArray[indexPath.row]] ;
    return cell ;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0:
            [self showProvinceMenu] ;
            break;
        case 1:
            [self showCityMenu] ;
            break;
        case 2:
            [self showDistrictMenu] ;
            break;
        default:
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 51 ;
}

- (void)ltCustomMenu:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"点击了wan") ;
    //省份点击
    if (self.provinceMenu) {
        proviceStr = MenuArray1[indexPath.row] ;
        
        if (MenuArray2.count == 1 && ![proviceStr isEqualToString:@"中国其他"]) {
            cityStr = @"所有区域" ;
        }
        else if ([proviceStr isEqualToString:@"中国其他"]) {
            cityStr = @"中国其他" ;
        }
        else{
            cityStr = MenuArray2[0] ;
        }
    
        if (MenuArray3.count == 1 && ![cityStr isEqualToString:@"中国其他"]) {
            districtStr = @"所有区域" ;
        }
        else if ([cityStr isEqualToString:@"中国其他"]) {
            districtStr = @"中国其他" ;
        }
        else{
            districtStr = MenuArray3[0] ;
        }
        
        [self modelwithProvince:proviceStr city:cityStr district:districtStr] ;
        [self initLocation] ;
        [locationTabelView reloadData] ;
        NSLog(@"点击了1") ;
    }
    
    //城市点击
    if (self.cityMenu) {
        cityStr = MenuArray2[indexPath.row] ;
        if (MenuArray3.count == 1 && ![cityStr isEqualToString:@"中国其他"]) {
            districtStr = @"所有区域" ;
        }
        else if ([cityStr isEqualToString:@"中国其他"]) {
            districtStr = @"中国其他" ;
        }
        else{
            districtStr = MenuArray3[0] ;
        }
        [self modelwithProvince:proviceStr city:cityStr district:districtStr] ;
        [self initLocation] ;
        [locationTabelView reloadData] ;
        NSLog(@"点击了2") ;
        
    }
    
    if (self.districtMenu) {
        districtStr = MenuArray3[indexPath.row] ;
        [self modelwithProvince:proviceStr city:cityStr district:districtStr] ;
        [self initLocation] ;
        [locationTabelView reloadData] ;
        NSLog(@"点击了3") ;
    }


}

- (void)showProvinceMenu
{
    __weak __typeof(self) weakSelf = self;
    if (!self.provinceMenu) {
        
        self.provinceMenu = [[LocationCustomMenu alloc] initWithDataArr:MenuArray1 origin:CGPointMake(100, 2) width:125 rowHeight:30];
        self.provinceMenu.delegate = self;
        self.provinceMenu.dismiss = ^() {
            weakSelf.provinceMenu = nil;
        };
        [self.view addSubview:_provinceMenu];
    } else {
        [_provinceMenu dismissWithCompletion:^(LocationCustomMenu *object) {
            weakSelf.provinceMenu = nil;
        }];
    }
    
}

- (void)showCityMenu
{
    __weak __typeof(self) weakSelf = self;
    if (!self.cityMenu) {
        
        self.cityMenu = [[LocationCustomMenu alloc] initWithDataArr:MenuArray2 origin:CGPointMake(100, 52) width:125 rowHeight:30];
        self.cityMenu.delegate = self;
        self.cityMenu.dismiss = ^() {
            weakSelf.cityMenu = nil;
        };
        [self.view addSubview:_cityMenu];
    } else {
        [_cityMenu dismissWithCompletion:^(LocationCustomMenu *object) {
            weakSelf.cityMenu = nil;
        }];
    }
    
}

- (void)showDistrictMenu
{
    __weak __typeof(self) weakSelf = self;
    if (!self.districtMenu) {
        
        self.districtMenu = [[LocationCustomMenu alloc] initWithDataArr:MenuArray3 origin:CGPointMake(100, 102) width:125 rowHeight:30];
        self.districtMenu.delegate = self;
        self.districtMenu.dismiss = ^() {
            weakSelf.districtMenu = nil;
        };
        [self.view addSubview:_districtMenu];
    } else {
        [_districtMenu dismissWithCompletion:^(LocationCustomMenu *object) {
            weakSelf.districtMenu = nil;
        }];
    }
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    // UITouch *touch = [touches anyObject];
    [self.provinceMenu dismissWithCompletion:nil] ;
    [self.cityMenu dismissWithCompletion:nil] ;
    [self.districtMenu dismissWithCompletion:nil] ;
    //    if (![self.menu]) {
    //        //        [self.menu dismissWithCompletion:nil];
    //        [self createNavbar] ;
    //    }
    
}

- (void)save
{
    SetViewController *vc = [self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-2];
    
    vc.location_model = [self modelwithProvince:proviceStr city:cityStr district:districtStr] ;
    
    [self.navigationController popToViewController:vc animated:NO];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
